package com.daodai.hjcjsystem.task;

import com.daodai.hjcjsystem.domain.po.DeviceEntity;
import com.daodai.hjcjsystem.mapper.CollectionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@RequiredArgsConstructor
public class AsyncTaskService {

    private final CollectionMapper collectionMapper;

    private final AtomicInteger queuedTaskCount = new AtomicInteger(0);


    // 获取当前排队任务数
    public int getQueuedTaskCount() {
        return queuedTaskCount.get();
    }
    /**
     * 将采集数据插入到device_realtime_value表中
     * @param deviceEntityList
     * @return
     */

    @Async
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 明确事务边界
    public void saveToRealTimeValue(List<DeviceEntity> deviceEntityList){
        queuedTaskCount.incrementAndGet(); // 任务开始前+1
        try {

            System.out.println("开启" + Thread.currentThread().getName() + "进行数据表device_realtime_value的写入操作......");
            //增加数据创建时间和更新时间
            deviceEntityList.forEach(deviceEntity -> {
                deviceEntity.setCreateTime(LocalDateTime.now());
                deviceEntity.setModifyTime(LocalDateTime.now());
            });

            collectionMapper.insertBatch(deviceEntityList);

            System.out.println( Thread.currentThread().getName() +  "数据插入表device_realtime_value成功！！");
        } finally {
            queuedTaskCount.decrementAndGet(); // 完成后-1
        }
    }

    /**
     * 更新采集值到表device_realtime_value_now中
     * @param deviceEntityList
     */
    @Async
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 明确事务边界
    public void updateToNowTable(List<DeviceEntity> deviceEntityList){
        queuedTaskCount.incrementAndGet(); // 任务开始前+1
        try {

            System.out.println("开启" + Thread.currentThread().getName() + "进行数据表device_realtime_value_now的更新操作......");
            int  batchSize = 20;//细分批次更新
            int total = deviceEntityList.size();
            //仅设置更新时间
            deviceEntityList.forEach(device ->{
                device.setModifyTime(LocalDateTime.now());
            });
            for (int i = 0; i < total ; i+=batchSize) {
                int end = Math.min(i + batchSize, total);
                List<DeviceEntity> subList = deviceEntityList.subList(i, end);
                collectionMapper.updateToNowTable(subList);
            }
            System.out.println(Thread.currentThread().getName() +  "数据更新表device_realtime_value_now成功！！");
        } finally {
            queuedTaskCount.decrementAndGet(); // 完成后-1
        }
    }
}
